import axios from 'axios'
import {
	Toast
} from 'vant'
import {
	setStore,
	getStore,
	removeStore
} from './storage'
// import VueCookies from 'vue-cookies'
// Vue.use(VueCookies)
// 根据环境不同引入不同api地址
import {
	baseApi,
	wechatAuthUrlFront,
	wechatAuthUrlTail,
	preLoginUrl
} from '@/config'

function GetQueryString(name) {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
	var r = window.location.search.substr(1).match(reg)
	if (r != null) return unescape(r[2])
	return null
}

// 提前设置token
function GetToken() {
	const code = GetQueryString('code')
	return new Promise(function(reslove, reject) {
		if (code !== '' && code != null && code !== undefined && code !== 'undefined') {
			// console.log('进入loginByMp请求')
			axios({
				method: 'post',
				url: baseApi + 'out2/ftms/login',
				data: {
					code: GetQueryString('code'),
          systemCode:'123'
				}

			}).then((res) => {
				// console.log(res.data)
				if (res.data.code === 0) {
					setStore('token', res.data.token)
				}
				reslove(res.data)
			})
		}

	})
}

function isLogin() {
	// 指定微信授权回调页面为当前页面，必须用 uriencode处理跳转地址
	var jumpUrl = wechatAuthUrlFront + encodeURIComponent(preLoginUrl) + wechatAuthUrlTail

	setTimeout(function() {
		location.href = jumpUrl
	}, 1500)

}

// create an axios instance
const service = axios.create({
	baseURL: baseApi, // url = base api url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 40000 // request timeout
})


// request拦截器 request interceptor
service.interceptors.request.use(
	async config => {
			// 不传递默认开启loading
			if (!config.hideloading) {
				// loading
				Toast.loading({
					forbidClick: true,
					duration: 0,
					message: '加载中...'
				})
			}
			if (!getStore('token') && GetQueryString('code')) {
				let res = await GetToken()
				// console.log(res + 'token')
				config.headers.token = res
			} else {
				config.headers.token = getStore('token')
			}
			config.headers['Access-Control-Allow-Headers'] = '*/*'
			return config
		},
		error => {
			// do something with request error
			// console.log(error) // for debug
			return Promise.reject(error)
		}
)
// respone拦截器
service.interceptors.response.use(
	response => {
		Toast.clear()
		// console.log(response.data)
		const res = response.data
		if (res.code && res.code !== 200) {
			// 登录超时,重新登录
			if (res.code === 401) {
				Toast.loading({
					message: '登陆校验...',
					forbidClick: true,
					duration: 3000
				})

				if (!GetQueryString('code')) {
					setStore('loginRequestUrl', window.location.href)
					isLogin()
				}
			}
			return Promise.reject(res || 'error')
		} else {
			return Promise.resolve(res)
		}
	},
	error => {
		Toast.clear()
		console.log('err' + error) // for debug
		return Promise.reject(error)
	}
)

export default service
